package xiaoqiang

import (
	"encoding/json"
	"fmt"
	"parking-lot-go-push/model/cars"
	"parking-lot-go-push/model/order"
	"parking-lot-go-push/mongodb"
)

type OutStruct struct {
	mongodb.CarsOutMongoDbStruct
}

// 小强进场推送
func (outData OutStruct) Out() {

	xiaoQiangPushLogger.Info(" ")
	xiaoQiangPushLogger.Info("---出场推送---")
	jsonData, _ := json.Marshal(outData)
	xiaoQiangPushLogger.Info(fmt.Sprintf("参数:%s", string(jsonData)))

	var err error

	//查询订单
	var orderStruct order.OrderStruct
	if _, err = orderStruct.FetchOrder(outData.OrderNo, 1, 1); err != nil {
		xiaoQiangPushLogger.Error(fmt.Sprintf("订单查询失败:%s", err.Error()))
		return
	}

	//查询小强订单
	var orderXiaoQiangStruct order.OrderXiaoqiangStruct
	orderXiaoQiangData, err := orderXiaoQiangStruct.FetchOrder(outData.OrderNo, 1)
	if err != nil {
		xiaoQiangPushLogger.Error(fmt.Sprintf("小强订单查询失败:%s", err.Error()))
		return
	}

	//超停状态
	if _, err = orderStruct.OverStop(outData.ParkCode, 1, outData.OrderNo); err != nil {
		xiaoQiangPushLogger.Error(err.Error())
		return
	}

	//查询订单补缴金额
	var orderXiaoQiangPaymentStruct order.OrderXiaoqiangPaymentStruct
	overshootPrice := orderXiaoQiangPaymentStruct.PaymentMoeny(outData.OrderNo, orderXiaoQiangData.XqOrderNo)

	//通知小强车辆出场
	xqEntryPushData := map[string]interface{}{
		"serviceType":    2002,
		"orderType":      1,
		"orderId":        orderXiaoQiangData.XqOrderNo,
		"parkId":         outData.ParkCode,
		"plateNumber":    outData.CarNumber,
		"startTime":      outData.InTime,
		"endTime":        outData.OutTime,
		"overshootPrice": overshootPrice,
	}

	//加密信息计算
	xqSigner := NewSigner()
	encryptedData, signature, err := xqSigner.EncryptAndSign(xqEntryPushData)
	if err != nil {
		xiaoQiangPushLogger.Error(fmt.Sprintf("小强参数加密失败:%s", err.Error()))
		return
	}

	var carsOutStruct cars.CarsOutStruct

	if err, _ := xqSigner.CurlPostJson(
		"inOutPark",
		map[string]interface{}{
			"data": encryptedData,
			"sign": signature,
		}); err != nil {
		xiaoQiangPushLogger.Error(fmt.Sprintf("推送小强出场信息失败:%s", err.Error()))

		//失败状态更新
		if err := carsOutStruct.PushError(outData.OrderNo, outData.PushErrNum); err != nil {
			xiaoQiangPushLogger.Error(err.Error())
		}
	} else {

		//拼接静态参数
		unBindCarData := map[string]interface{}{
			"carId":      outData.CarNumber,
			"phone":      orderXiaoQiangData.Mobile,
			"carType":    outData.CarType,
			"carnoColor": outData.CarNoColor,
		}

		//成功状态更新
		if err := carsOutStruct.PushSuccess(outData.OrderNo, outData.OutTime, 1, unBindCarData); err != nil {
			xiaoQiangPushLogger.Error(err.Error())
		}

	}
}
